const Koa = require("koa");
const app = new Koa();
const views = require("koa-views");
const json = require("koa-json");
const onerror = require("koa-onerror");
const koaBody = require("koa-body");
const logger = require("koa-logger");
const cors = require("koa2-cors");
const Config = require("./module/config.js");
const fs = require("fs");
const utils = require("./utils");
const { getTime } = utils;

//路由
const users = require("./routes/users");

//日志文件系统
let loggerWrite = fs.createWriteStream("log.txt", {
  flags: "a", // 'a' means appending (old data will be preserved)
});

// error handler
onerror(app);

// middlewares
// app.use(bodyparser({
//   enableTypes:['json', 'form', 'text']
// }))
app.use(json());
app.use(logger());
app.use(require("koa-static")(__dirname + "/public"));

//koa-body
app.use(
  koaBody({
    multipart: true,
    formidable: {
      maxFileSize: 1000 * 1024 * 1024,
    },
  })
);

//跨域
app.use(
  cors({
    allowMethods: ["GET", "POST", "DELETE"],
  })
);

app.use(
  views(__dirname + "/views", {
    extension: "pug",
  })
);

// logger
app.use(async (ctx, next) => {
  // console.log("logger", ctx);
  const start = new Date();
  await next();
  const ms = new Date() - start;
  let log = `${ctx.method} ${ctx.url} - ${ms}ms - ${getTime()}`;
  loggerWrite.write(log + "\n");
  console.log(log);
});
// routes
// app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods());

// error-handling
app.on("error", (err, ctx) => {
  console.error("server error", err, ctx);
});

module.exports = app;

/*qpi文档执行命令*/
// apidoc -i routes/ -o public/apidoc/
//全局安装
// npm install apidoc -g
//访问接口文档
// http://localhost:3300/apidoc/index.html
